<template>
  <div class="article-detail-page">
    <div class="article-layout">
      <!-- Main content -->
      <div class="article-main">
        <div class="article-container card">
          <!-- Article header -->
          <div class="article-header">
            <h1 class="article-title">{{ article.articleTitle }}</h1>

            <div class="article-meta">
              <div class="author-info">
                <img :src="article.author.avatar" :alt="article.author.nickName" class="author-avatar" v-if="article.author && article.author.avatar">
                <img src="~assets/icon/avatar.png" :alt="article.author.nickName" class="author-avatar" v-else>
                <div class="author-details">
                  <div class="author-name">{{ article.author && article.author.nickName? article.author.nickName:'未知用户'  }}</div>
                  <div class="article-date">{{ formatDate(article.createTime) }}</div>
                </div>
              </div>

              <div class="article-stats">
                <div class="stat-item">
                  <el-icon><View /></el-icon>
                  <span>{{formatCount(article.articleViewCount)  }}次阅读</span>
                </div>
              </div>
            </div>

            <div class="article-tags">
              <span v-for="tag in article.articleTags.split(',')" :key="tag" class="article-tag">
                {{ tag }}
              </span>
            </div>
          </div>
          <VditorPreview :content="article.articleContent" class="article-content" id="preview-container" />

          <div class="article-footer">
            <div class="action-bar">
              <div class="action-item">
                <el-button  class="like-btn" :class="{ active: isLiked }" @click="toggleLike">
                  <el-icon><LikeXin /></el-icon>
                  <span>{{ formatCount(article.articleGoodCnt) }}</span>
                </el-button>
              </div>

              <div class="action-item">
                <el-button class="comment-btn">
                  <el-icon><ChatDotRound /></el-icon>
                  <span>评论 {{ formatCount(article.articleCommentCount) }}</span>
                </el-button>
              </div>

              <div class="action-item">
                <el-button class="collect-btn">
                  <el-icon><Star /></el-icon>
                  <span>收藏{{ formatCount(article.articleCollectCnt) }}</span>
                </el-button>
              </div>

              <div class="action-item">
                <el-dropdown trigger="click">
                  <el-button class="share-btn">
                    <el-icon><Share /></el-icon>
                    <span>分享</span>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item>
                        <div class="share-item">
                          <el-icon><Link /></el-icon>
                          <span>复制链接</span>
                        </div>
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <div class="share-item">
                          <img src="https://lf3-cdn-tos.bytescm.com/obj/static/xitu_juejin_web/685e7b8e27c5e039243c366275873f8e.svg" alt="微信" class="share-icon">
                          <span>微信</span>
                        </div>
                      </el-dropdown-item>
                      <el-dropdown-item>
                        <div class="share-item">
                          <img src="https://lf3-cdn-tos.bytescm.com/obj/static/xitu_juejin_web/fcd928cedcc1a9c67b88aa5a53da952f.svg" alt="微博" class="share-icon">
                          <span>微博</span>
                        </div>
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </div>
        </div>

        <!-- Comments section -->
        <div class="comments-section card">
          <div class="comments-header">
            <h3>评论 ({{ formatCount(article.articleCommentCount) }})</h3>
          </div>

          <div class="comment-form">
            <el-input
              v-model="commentContent"
              type="textarea"
              :rows="3"
              placeholder="输入评论..."
              resize="none"
            />
            <div class="form-footer">
              <el-button type="primary" :disabled="!commentContent.trim()">发布评论</el-button>
            </div>
          </div>

          <div v-if="article.comments && article.comments.length > 0" class="comments-list">
            <div v-for="comment in article.comments" :key="comment.id" class="comment-item">
              <div class="comment-author">
                <img :src="comment.author.avatar" :alt="comment.author.name" class="comment-avatar">
                <div class="comment-author-info">
                  <div class="comment-author-name">{{ comment.author.name }}</div>
                  <div class="comment-date">{{ formatDate(comment.createdAt) }}</div>
                </div>
              </div>
              <div class="comment-content">{{ comment.content }}</div>
              <div class="comment-actions">
                <div class="action-btn">
                  <el-icon><LikeXin /></el-icon>
                  <span>{{ comment.likeCount }}</span>
                </div>
                <div class="action-btn">
                  <el-icon><ChatDotRound /></el-icon>
                  <span>回复</span>
                </div>
              </div>
            </div>
          </div>
          <div v-else class="empty-comments">
            <el-empty description="暂无评论，快来发表第一条评论吧" />
          </div>
        </div>
      </div>

      <!-- Sidebar -->
      <div class="article-sidebar">
        <!-- Author card -->
        <div class="author-card card">
          <div class="author-header">
            <img :src="article.author.avatar" :alt="article.author.nickName" class="author-avatar" v-if="article.author && article.author.avatar">
            <img src="~assets/icon/avatar.png" :alt="article.author.nickName" class="author-avatar" v-else>

            <div class="author-info">
              <div class="author-name">{{ article.author && article.author.nickName? article.author.nickName:'未知用户' }}</div>
              <div class="author-title">{{ article.author && article.author.title? article.author.title:'由你来评价我！' }}</div>
            </div>
          </div>

          <div class="author-stats">
            <div class="stat-item">
              <div class="stat-value">{{ article.author && article.author.articleCount? article.author.articleCount:1 }}</div>
              <div class="stat-label">文章</div>
            </div>
            <div class="stat-item">
              <div class="stat-value">{{ article.author && article.author.followerCount? article.author.followerCount:1  }}</div>
              <div class="stat-label">关注者</div>
            </div>
          </div>

          <div class="author-action">
            <el-button type="primary" class="follow-btn">关注</el-button>
          </div>
        </div>

        <!-- Related articles -->
        <div class="related-articles card">
          <div class="section-header">
            <h3>相关文章</h3>
          </div>

          <div class="related-list">
            <div v-for="related in relatedArticles" :key="related.id" class="related-item">
              <NuxtLink :to="`/article/${related.id}`" class="related-title">
                {{ related.title }}
              </NuxtLink>
              <div class="related-meta">
                <span>{{ related.viewCount }} 阅读</span>
              </div>
            </div>
          </div>
        </div>

        <!-- Ad banner -->
        <div class="ad-banner card">
          <img src="https://images.pexels.com/photos/270348/pexels-photo-270348.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=2"
               alt="Advertisement"
               class="ad-image">
          <div class="ad-label">广告</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { useRoute } from 'vue-router'
import { formatCount,formatDate } from '~/composables/globals'
import { useArticleDetail } from '~/composables/useArticleDetail'
// Get article ID from route
const route = useRoute()
// 确保初始值正确处理
const articleId = computed(() => route.params.id?.toString() || '0');
const { article, relatedArticles } = useArticleDetail(route.params.id)

// 监听路由变化
watch(
    () => route.params.id,
    (newId, oldId) => {
      if (newId !== oldId) {

      }
    },
    { immediate: true }
);
// Fetch article details


// Comment form
const commentContent = ref('')
const tocArray = ref([])
const detailDirectory = ref('preview-container') // 需要绑定对应的 DOM 元素
// Like state
const isLiked = ref(false)
const toggleLike = () => {
  isLiked.value = !isLiked.value
  // In a real app, this would update the server
}

/*onMounted(() => {
  generateDirectory()
})*/
/*const generateDirectory = () => {
  nextTick(() => {
    const tocTags = ["H1", "H2", "H3", "H4"]
    const tempArray = []

    // 通过 ref 获取 DOM 元素
    const element = detailDirectory.value
    if (!element) return

    // 更安全的 DOM 节点访问方式（原路径可能存在隐患）
    const markdownBody = element.querySelector('.markdown-body') // 根据实际 DOM 结构调整
    if (!markdownBody) return

    const nodes = markdownBody.childNodes
    nodes.forEach(item => {
      const tagName = item.tagName
      if (!tagName || !tocTags.includes(tagName.toUpperCase())) return

      const anchor = item.querySelector('a')
      if (!anchor) return

      const id = anchor.id
      const targetElement = document.getElementById(id)
      if (!targetElement) return

      tempArray.push({
        id,
        text: item.textContent || "",
        level: Number(tagName.substring(1)),
        pos: targetElement.offsetTop
      })
    })

    tocArray.value = tempArray
  })
}*/

// SEO metadata
useHead({
  title: computed(() => article.value?.title ? `${article.value.title} - 掘金` : '文章详情 - 掘金'),
  meta: [
    {
      name: 'description',
      content: computed(() => article.value?.description || '掘金技术社区文章详情页')
    }
  ]
})
</script>

<style lang="scss" scoped>
.article-detail-page {
  margin-top: $header-height + $spacing-md;
}

.article-layout {
  display: flex;
  gap: $spacing-md;

  .article-main {
    flex: 1;
    min-width: 0;
  }

  .article-sidebar {
    width: 300px;
    flex-shrink: 0;
  }
}

.article-container {
  padding: $spacing-lg;
}

.article-header {
  margin-bottom: $spacing-lg;

  .article-title {
    font-size: 24px;
    font-weight: 600;
    margin-bottom: $spacing-md;
    line-height: 1.4;
  }

  .article-meta {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: $spacing-md;

    .author-info {
      display: flex;
      align-items: center;

      .author-avatar {
        width: 40px;
        height: 40px;
        border-radius: 50%;
        margin-right: $spacing-sm;
      }

      .author-details {
        .author-name {
          font-size: 16px;
          font-weight: 500;
          margin-bottom: 2px;
        }

        .article-date {
          font-size: 13px;
          color: $text-secondary;
        }
      }
    }

    .article-stats {
      display: flex;
      align-items: center;

      .stat-item {
        display: flex;
        align-items: center;
        font-size: 14px;
        color: $text-secondary;

        .el-icon {
          margin-right: 4px;
        }
      }
    }
  }

  .article-tags {
    display: flex;
    flex-wrap: wrap;
    gap: $spacing-xs;
    margin-bottom: $spacing-md;

    .article-tag {
      font-size: 13px;
      color: $primary-color;
      background-color: $primary-light;
      padding: 4px $spacing-sm;
      border-radius: $border-radius-sm;
    }
  }
}

.article-content {
  font-size: 16px;
  line-height: 1.8;
  color: $text-primary;

  p {
    margin-bottom: $spacing-md;
  }

  h1, h2, h3, h4, h5, h6 {
    margin-top: $spacing-lg;
    margin-bottom: $spacing-sm;
    font-weight: 600;
  }

  img {
    max-width: 100%;
    margin: $spacing-md 0;
    border-radius: $border-radius-md;
  }

  pre {
    background-color: #f8f8f8;
    padding: $spacing-md;
    border-radius: $border-radius-md;
    overflow-x: auto;
    margin: $spacing-md 0;
  }

  code {
    font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, Courier, monospace;
    font-size: 14px;
  }

  blockquote {
    border-left: 4px solid $primary-color;
    padding-left: $spacing-md;
    color: $text-regular;
    margin: $spacing-md 0;
  }

  ul, ol {
    margin: $spacing-md 0;
    padding-left: $spacing-lg;
  }
}

.article-footer {
  margin-top: $spacing-lg;
  padding-top: $spacing-lg;
  border-top: 1px solid $border-color;

  .action-bar {
    display: flex;
    justify-content: center;
    gap: $spacing-md;

    .action-item {
      .el-button {
        display: flex;
        align-items: center;

        .el-icon {
          margin-right: $spacing-xs;
        }
      }

      .like-btn {
        &.active {
          background-color: $primary-color;
          color: #fff;
        }
      }
    }
  }
}

.comments-section {
  margin-top: $spacing-md;
}

.comments-header {
  padding: $spacing-md;
  border-bottom: 1px solid $border-color;

  h3 {
    font-size: 18px;
    font-weight: 500;
  }
}

.comment-form {
  padding: $spacing-md;
  border-bottom: 1px solid $border-color;

  .form-footer {
    display: flex;
    justify-content: flex-end;
    margin-top: $spacing-sm;
  }
}

.comments-list {
  .comment-item {
    padding: $spacing-md;
    border-bottom: 1px solid $border-color;

    &:last-child {
      border-bottom: none;
    }

    .comment-author {
      display: flex;
      align-items: center;
      margin-bottom: $spacing-sm;

      .comment-avatar {
        width: 36px;
        height: 36px;
        border-radius: 50%;
        margin-right: $spacing-sm;
      }

      .comment-author-info {
        .comment-author-name {
          font-size: 14px;
          font-weight: 500;
        }

        .comment-date {
          font-size: 12px;
          color: $text-secondary;
        }
      }
    }

    .comment-content {
      font-size: 14px;
      margin-bottom: $spacing-sm;
      color: $text-primary;
      line-height: 1.6;
    }

    .comment-actions {
      display: flex;
      gap: $spacing-md;

      .action-btn {
        display: flex;
        align-items: center;
        font-size: 13px;
        color: $text-secondary;
        cursor: pointer;

        &:hover {
          color: $primary-color;
        }

        .el-icon {
          margin-right: 4px;
          font-size: 14px;
        }
      }
    }
  }
}

.empty-comments {
  padding: $spacing-lg;
}

.author-card {
  padding: $spacing-md;

  .author-header {
    display: flex;
    align-items: center;
    margin-bottom: $spacing-md;

    .author-avatar {
      width: 48px;
      height: 48px;
      border-radius: 50%;
      margin-right: $spacing-sm;
    }

    .author-info {
      .author-name {
        font-size: 16px;
        font-weight: 500;
        margin-bottom: 2px;
      }

      .author-title {
        font-size: 13px;
        color: $text-secondary;
      }
    }
  }

  .author-stats {
    display: flex;
    margin-bottom: $spacing-md;

    .stat-item {
      flex: 1;
      text-align: center;
      padding: $spacing-xs 0;

      .stat-value {
        font-size: 16px;
        font-weight: 500;
        margin-bottom: 2px;
      }

      .stat-label {
        font-size: 13px;
        color: $text-secondary;
      }
    }
  }

  .author-action {
    .follow-btn {
      width: 100%;
    }
  }
}

.related-articles {
  margin-top: $spacing-md;

  .section-header {
    padding: $spacing-md;
    border-bottom: 1px solid $border-color;

    h3 {
      font-size: 16px;
      font-weight: 500;
    }
  }

  .related-list {
    .related-item {
      padding: $spacing-md;
      border-bottom: 1px solid $border-color;

      &:last-child {
        border-bottom: none;
      }

      .related-title {
        font-size: 14px;
        margin-bottom: 4px;
        color: $text-primary;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
        overflow: hidden;

        &:hover {
          color: $primary-color;
        }
      }

      .related-meta {
        font-size: 12px;
        color: $text-secondary;
      }
    }
  }
}

.ad-banner {
  margin-top: $spacing-md;
  position: relative;
  overflow: hidden;
  padding: 0;

  .ad-image {
    width: 100%;
    display: block;
  }

  .ad-label {
    position: absolute;
    bottom: $spacing-xs;
    right: $spacing-xs;
    background-color: rgba(0, 0, 0, 0.6);
    color: #fff;
    font-size: 12px;
    padding: 2px 4px;
    border-radius: $border-radius-sm;
  }
}

.share-item {
  display: flex;
  align-items: center;

  .el-icon, .share-icon {
    margin-right: $spacing-xs;
    width: 16px;
    height: 16px;
  }
}

@media (max-width: $breakpoint-lg) {
  .article-layout {
    flex-direction: column;

    .article-sidebar {
      width: 100%;
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
      gap: $spacing-md;
    }
  }
}

@media (max-width: $breakpoint-md) {
  .article-container {
    padding: $spacing-md;
  }

  .article-header {
    .article-title {
      font-size: 20px;
    }
  }

  .article-footer {
    .action-bar {
      flex-wrap: wrap;

      .action-item {
        flex: 1;
        min-width: 40%;

        .el-button {
          width: 100%;
        }
      }
    }
  }
}
</style>
